package cn.xyafu.lost.dialog;

import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.xyafu.lost.R;
import cn.xyafu.lost.pojo.User;
import cn.xyafu.lost.utils.LostOpenHelper;
import cn.xyafu.lost.utils.ResponseEntityToModule;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class    MineDialog extends Dialog {

    // 更新标志
    Boolean flag = false;

    LostOpenHelper openHelper;
    // (1). 创建OkHttpCLient对象
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    OkHttpClient client;

    public MineDialog(@NonNull Context context) {
        super(context);
        // 取消系统返回键
        setCancelable(false);
        // 绑定布局文件
        setContentView(R.layout.dialog_mine);
        // 数据库
        openHelper = new LostOpenHelper(getContext(),"lostdb",null,1);
        // 设置okhttp
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        client = builder.build();

        TextView tv_show_name = findViewById(R.id.tv_show_name);
        final EditText edt_update_sex = findViewById(R.id.edt_update_sex);
        final EditText edt_update_email = findViewById(R.id.edt_update_email);
        Button btn_update = findViewById(R.id.btn_update);
        Button btn_cancel = findViewById(R.id.btn_cancel);

        String username = "";
        String sex = "";
        String email = "";
        String uid = "7";
        SQLiteDatabase db = openHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from t_user", null);
        cursor.moveToFirst();	//移至第一行
        for(int i = 0; i < cursor.getCount(); i++){	//遍历每行数据
            // 获取列数据
            username =  cursor.getString(1);
            sex = cursor.getString(4);
            email = cursor.getString(5);
            uid = cursor.getString(6);
        }
        tv_show_name.setText(username);
        edt_update_sex.setText(sex);
        edt_update_email.setText(email);

        final String finalUid = uid;
        // 设置监听事件，匹配操作按钮
        Button.OnClickListener btnListener = new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                switch(v.getId()){
                    case R.id.btn_update:
                        String usex = edt_update_sex.getText().toString().trim();
                        String uemail = edt_update_email.getText().toString().trim();
                        updateUser(usex,uemail, finalUid);
                        break;
                    case R.id.btn_cancel:
                        break;
                }
                dismiss();
            }
        };
        btn_update.setOnClickListener(btnListener);
        btn_cancel.setOnClickListener(btnListener);
    }

    private User getUser() {
        final User[] user = {null};
        // (2). 创建Request对象
        Request request = new Request.Builder().url(
                "http://localhost/Lost_ssm/android/getSession").get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                user[0] = (User) ResponseEntityToModule.parseJsonToModule(response.body().string(), User.class);

            }
        });
        return user[0];
    }

    // 更新数据
    private void updateUser(String usex,String uemail,String uid){
        //  发起网络请求
        // (2). 创建Request对象
        Request request = new Request.Builder().url("http://localhost/Lost_ssm/android/updateUser?usex="+ usex +"&uemail="+ uemail +"&uid="+ uid).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                User user = (User) ResponseEntityToModule.parseJsonToModule(response.body().string(), User.class);
                if (user != null){
                    updateSQLite(user);
                    flag = true;
                }

            }
        });
    }

    // 更新数据后，更新本地数据库
    private void updateSQLite(User user){
        SQLiteDatabase db = openHelper.getWritableDatabase();
        db.execSQL("update t_user set usex=?,uemail=?;",new String[]{user.getUsex(), user.getUemail()});
        db.close();

    }
    
}
